//
//  MBShowViewController.m
//  MiBaoTu
//
//  Created by 彭鹏 on 16/9/18.
//  Copyright © 2016年 com.caesartech15. All rights reserved.
//

#import "MBShowViewController.h"
#import "MBSpaceMyParentChildShowTabbarView.h"
#import "MBTheNewCell.h"
#import "MBSpacePeopelViewController.h"
#import "MBDetailViewController.h"
#import "MBTheNewICell.h"

#import "MBSongDetailForIController.h"
#import "MBDetailViewForIpadController.h"
static NSString *ID = @"MBTheNewCell";
@interface MBShowViewController ()<MBSpaceMyParentChildShowTabbarViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource>{
    int             page;
    NSMutableArray  *_mutArr;
}
@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, strong) UICollectionView *collectionView;
@end

@implementation MBShowViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

}
- (void)viewDidLoad {
    [super viewDidLoad];

    page = 1;
    _mutArr = [[NSMutableArray alloc]init];

    
    [self setupNavBar];
    [self onCreateUI];
    
    [self onLoadNew];
}

- (void)setupNavBar {
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"fanhui"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]style:UIBarButtonItemStylePlain target:self action:@selector(navigationBackButton)];
    
    [self setRightPlayerItem];
}

-(void)navigationBackButton {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 点击事件
- (void)playingPage {
    NSLog(@"跳转到点击页面");
}

#pragma mark - Actions
- (void)onCreateUI
{
    float heith = 0;
    heith = 80*PERCEN;
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.flowLayout = flowLayout;
    // 设置cell的尺寸
    flowLayout.itemSize = CGSizeMake(100, 100);
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,0, SCREEN_WIDTH, self.view.height-(heith > 0 ? 80*PERCEN+NAV_HEIGHT : 0))collectionViewLayout:flowLayout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_collectionView];
    // 加载xib文件
    UINib *nib = [UINib nibWithNibName:@"MBTheNewCell" bundle:nil];
    [self.collectionView registerNib:nib forCellWithReuseIdentifier:ID];
    //注册iPad cell
    [self.collectionView registerClass:[MBTheNewICell class] forCellWithReuseIdentifier:@"MBTheNewICell"];
    [self.collectionView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(onLoadNew)];
    [self.collectionView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(onLoadMore)];
}

#pragma mark - 加载数据
- (void)onLoadNew
{
    page = 1;
    [self loadData];
}

- (void)onLoadMore
{
    ++page;
    [self loadData];
}

- (void)loadData
{
    NSNumber *num = @2;
    if (self.type == 0) {
        num = @2;
    }
    else if (self.type == 1) {
        num = @1;
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:FAMILYSHOW_STARTSHO_URL_PATH,num,[NSNumber numberWithInt:page]] view:nil success:^(id json) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [_collectionView.header endRefreshing];
        [_collectionView.footer endRefreshing];
     
       
        if ([json[@"ret_code"] integerValue]==0) {
            NSArray *arr = json[@"data"];
            if (arr.count > 0) {
                if (page == 1) {
                    [_mutArr removeAllObjects];
                }
                [_mutArr addObjectsFromArray:arr];
            }
            [_collectionView reloadData];
        } else {
            [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [_collectionView.header endRefreshing];
        [_collectionView.footer endRefreshing];
    }];
}

#pragma mark - 选择器
- (void)onSelectItemForView:(MBSpaceMyParentChildShowTabbarView *)view withIndex:(NSInteger)selectIndex
{
    if (selectIndex < 2) {
        self.type = (int)selectIndex;
        [self onLoadNew];
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return _mutArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (ISIPAD) {
        MBTheNewICell*cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"MBTheNewICell"forIndexPath:indexPath];
//        cell.bigImageView.image = [UIImage imageNamed:@"bg_qzxbf"];
//        cell.smallTitle.text = @"迷路之后找回家";
//        cell.iconImageView.image = [UIImage imageNamed:@"baba_zl"];
//        cell.bigTitle.text = @"雪儿的妈妈";
//
        cell.dataDic=[_mutArr objectAtIndex:indexPath.row];
        return cell;

    }
    MBTheNewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    if (_mutArr.count > indexPath.row) {
        NSDictionary *dic = [_mutArr objectAtIndex:indexPath.row];
        
        //封面
        NSString *CoverPath = [dic objectForKey:@"CoverPath"];
        if ([CoverPath isKindOfClass:[NSNull class]]) {
            cell.bigImageView.image = [UIImage imageNamed:@"qzx_player_bg"];
        } else {
            if (CoverPath.length == 0) {
                cell.bigImageView.image = [UIImage imageNamed:@"qzx_player_bg"];
            } else {
                [cell.bigImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,CoverPath]] placeholderImage:[UIImage imageNamed:@"qzx_player_bg"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                    cell.bigImageView.image = [self getCenterImg:image withImgView:cell.bigImageView];
                }];
            }
        }
        cell.bigImageView.layer.cornerRadius = 5.;
        cell.bigImageView.layer.masksToBounds = YES;
        //标题
        cell.smallTitle.text = [NSString stringWithFormat:@"%@",[dic objectForKey:@"Sentiment"]];
        //人物头像
        NSString *FaceImg = [dic objectForKey:@"FaceImg"];
        if ([FaceImg isKindOfClass:[NSNull class]]) {
            cell.iconImageView.image = [UIImage imageNamed:@"xiaobian_bg"];
        } else {
            [cell.iconImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,FaceImg]] placeholderImage:[UIImage imageNamed:@"xiaobian_bg"]];
            cell.iconImageView.layer.cornerRadius = cell.iconImageView.height/2.;
            cell.iconImageView.layer.masksToBounds = YES;
        }
        //昵称
        cell.bigTitle.text = [NSString stringWithFormat:@"%@",[dic objectForKey:@"NickName"]];
    }
    
    return cell;
}
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    if (ISIPAD) {
          return UIEdgeInsetsMake(30*PERCEN, 80*PERCEN,80*PERCEN, 80*PERCEN);
    }
    return UIEdgeInsetsMake(0,0,0,0);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (ISIPAD) {
        float width = (SCREEN_WIDTH-240*PERCEN)/2;
        return CGSizeMake(width, width/904*700);
    }
    float itemWidth = ( SCREEN_WIDTH - 10*PERCEN)/2.;
    return CGSizeMake(itemWidth, 145);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    if (ISIPAD) {
        return 80*PERCEN;
    }
    return 1;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    if (ISIPAD) {
        return 80*PERCEN;
    }
    return 1;
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    UserManager *manager = [UserManager standerDefult];
    
    NSString *idStr ;
    if (manager.audioPlayerType != AudioPLayerType_Qinzix) {
        //初次进入
        idStr = @"";
        manager.audioPlayerType = AudioPLayerType_Qinzix;
    } else {
        //2次进入
        NSInteger selectIndex = manager.selectMusicIndex;
        NSArray *arr = manager.musicArr;
        Music *dics = [arr objectAtIndex:selectIndex];
        idStr = [NSString stringWithFormat:@"%@",dics.ID];
    }
    [manager setSelectMusicIndex:indexPath.row];
    [manager.musicArr removeAllObjects];
    [manager.musicArr addObjectsFromArray:[manager onTurnArrayFormQingZiXiuArray:_mutArr]];
    manager.selectMusicIndex = indexPath.row;
    [manager.qinzixiuArr removeAllObjects];
    [manager.qinzixiuArr addObjectsFromArray:_mutArr];
    if (ISIPAD) {
//        MBSongDetailForIController*song=[[MBSongDetailForIController alloc]init];
//        song.type=IdentityType_son;
//        
//        song.selectMusicID=idStr;
//        song.dataAllArr=_mutArr;
//        [self.navigationController pushViewController:song animated:YES];
        MBDetailViewForIpadController*childShowVC=[[MBDetailViewForIpadController alloc]init];
        childShowVC.selectMusicID=idStr;
        [childShowVC.dataAllArr addObjectsFromArray:_mutArr];
        [self.navigationController pushViewController:childShowVC animated:YES];
        return;
    }
    MBDetailViewController *childShowVC = [[MBDetailViewController alloc] init];
    childShowVC.selectMusicID=idStr;
    [childShowVC.dataAllArr addObjectsFromArray:_mutArr];
    [self.navigationController pushViewController:childShowVC animated:YES];
   
    
}

@end
